package com.star.oauth2.authserver.config;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.time.Duration;
import java.util.UUID;

import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.core.oidc.OidcScopes;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.server.authorization.client.InMemoryRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer;
import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings;
import org.springframework.security.oauth2.server.authorization.settings.ClientSettings;
import org.springframework.security.oauth2.server.authorization.settings.TokenSettings;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint;
import org.springframework.security.web.util.matcher.MediaTypeRequestMatcher;

/**
 * OAuth2授权服务器配置
 * <p>
 * 配置内容：
 * 1. 授权服务器安全配置
 * 2. 客户端注册信息
 * 3. 用户信息
 * 4. JWT密钥对
 * 5. 令牌设置
 *
 * @author star
 */
@Configuration
@EnableWebSecurity
public class AuthorizationServerConfig {

    /**
     * 授权服务器安全过滤器链
     * 配置OAuth2授权服务器的各种端点
     */
    @Bean
    @Order(1)
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http)
            throws Exception {
        // 应用OAuth2授权服务器的默认配置
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);

        http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
                // 启用OpenID Connect 1.0
                .oidc(Customizer.withDefaults());

        http
                // 未认证时重定向到登录页面
                .exceptionHandling((exceptions) -> exceptions
                        .defaultAuthenticationEntryPointFor(
                                new LoginUrlAuthenticationEntryPoint("/login"),
                                new MediaTypeRequestMatcher(MediaType.TEXT_HTML)
                        )
                )
                // 支持JWT令牌
                .oauth2ResourceServer((resourceServer) -> resourceServer
                        .jwt(Customizer.withDefaults()));

        return http.build();
    }

    /**
     * 标准Web安全配置
     * 配置登录页面和基本的安全规则
     */
    @Bean
    @Order(2)
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http)
            throws Exception {
        http
                .authorizeHttpRequests((authorize) -> authorize
                        // 允许访问首页（不需要登录）
                        .requestMatchers("/").permitAll()
                        // 允许访问错误页面和调试端点
                        .requestMatchers("/error", "/debug/**").permitAll()
                        // 允许访问静态资源
                        .requestMatchers("/css/**", "/js/**", "/images/**", "/webjars/**").permitAll()
                        // 允许访问OAuth2服务发现端点
                        .requestMatchers("/.well-known/**").permitAll()
                        // 其他所有请求需要认证
                        .anyRequest().authenticated()
                )
                // 启用表单登录
                .formLogin(form -> form
                        // 使用自定义登录页面
                        .loginPage("/login")
                        // 登录成功后重定向到原始请求的URL（OAuth2授权流程）
                        .permitAll()
                )
                // 启用登出功能
                .logout(logout -> logout
                        .logoutSuccessUrl("/login?logout")
                        .permitAll()
                );

        return http.build();
    }

    /**
     * 注册OAuth2客户端
     * <p>
     * 客户端配置说明：
     * - client_id: oauth2-client
     * - client_secret: secret（加密后存储）
     * - redirect_uri: http://localhost:8080/login/oauth2/code/oauth2-client (推荐)
     * http://127.0.0.1:8080/login/oauth2/code/oauth2-client (备用)
     * - scope: openid, profile, message.read, message.write
     * - grant_type: authorization_code, refresh_token
     */
    @Bean
    public RegisteredClientRepository registeredClientRepository(PasswordEncoder passwordEncoder) {
        RegisteredClient oidcClient = RegisteredClient.withId(UUID.randomUUID().toString())
                // 客户端ID
                .clientId("oauth2-client")
                // 客户端密钥（实际项目中应该加密存储）
                .clientSecret(passwordEncoder.encode("secret"))
                // 客户端认证方法
                .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
                .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
                // 授权类型：授权码模式
                .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
                // 授权类型：刷新令牌
                .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
                // 回调地址（授权成功后重定向的地址，用于接收授权码）
                // 这个地址会出现在浏览器地址栏中，格式：http://localhost:8080/callback?code=xxx&state=yyy
                // 由于我们没有客户端应用监听这个地址，浏览器会显示"无法访问"，但可以从地址栏复制code
                .redirectUri("http://localhost:8080/callback")
                // 如果需要支持其他回调地址，可以添加：
                // .redirectUri("http://localhost:3000/auth/callback")  // 前端应用
                // .redirectUri("https://myapp.com/oauth/callback")     // 生产环境
                // 授权范围
                .scope(OidcScopes.OPENID)
                .scope(OidcScopes.PROFILE)
                .scope("message.read")
                .scope("message.write")
                // 客户端设置
                .clientSettings(ClientSettings.builder()
                        // 跳过授权确认页面，自动授权所有请求的scope
                        .requireAuthorizationConsent(false)
                        .build())
                // 令牌设置
                .tokenSettings(TokenSettings.builder()
                        // 访问令牌有效期：30分钟
                        .accessTokenTimeToLive(Duration.ofMinutes(30))
                        // 刷新令牌有效期：7天
                        .refreshTokenTimeToLive(Duration.ofDays(7))
                        // 刷新令牌时重新使用旧的刷新令牌
                        .reuseRefreshTokens(true)
                        .build())
                .build();

        return new InMemoryRegisteredClientRepository(oidcClient);
    }

    /**
     * 配置JWT解码器
     * 用于验证JWT令牌
     */
    @Bean
    public JwtDecoder jwtDecoder(JWKSource<SecurityContext> jwkSource) {
        return OAuth2AuthorizationServerConfiguration.jwtDecoder(jwkSource);
    }

    /**
     * 配置JWK源
     * 用于签名JWT令牌
     */
    @Bean
    public JWKSource<SecurityContext> jwkSource() {
        KeyPair keyPair = generateRsaKey();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        RSAKey rsaKey = new RSAKey.Builder(publicKey)
                .privateKey(privateKey)
                .keyID(UUID.randomUUID().toString())
                .build();
        JWKSet jwkSet = new JWKSet(rsaKey);
        return new ImmutableJWKSet<>(jwkSet);
    }

    /**
     * 生成RSA密钥对
     * 用于JWT签名
     */
    private static KeyPair generateRsaKey() {
        KeyPair keyPair;
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(2048);
            keyPair = keyPairGenerator.generateKeyPair();
        } catch (Exception ex) {
            throw new IllegalStateException(ex);
        }
        return keyPair;
    }

    /**
     * 授权服务器设置
     * 配置授权服务器的各种端点URL
     */
    @Bean
    public AuthorizationServerSettings authorizationServerSettings() {
        return AuthorizationServerSettings.builder()
                // 授权服务器地址
                .issuer("http://localhost:9000")
                .authorizationEndpoint("/oauth2/authorize")
                .tokenEndpoint("/oauth2/token")

                .build();
    }

    /**
     * 配置用户信息服务
     * <p>
     * 测试用户：
     * - 用户名: user / 密码: password（普通用户）
     * - 用户名: admin / 密码: password（管理员）
     */
    @Bean
    public UserDetailsService userDetailsService(PasswordEncoder passwordEncoder) {
        UserDetails user = User.builder()
                .username("user")
                .password(passwordEncoder.encode("password"))
                .roles("USER")
                .build();

        UserDetails admin = User.builder()
                .username("admin")
                .password(passwordEncoder.encode("password"))
                .roles("USER", "ADMIN")
                .build();

        return new InMemoryUserDetailsManager(user, admin);
    }

    /**
     * 密码编码器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}

